<template>
  <div class="add-service">
    <div class="add-service__con">
      <div class="ismemory pb20">
        <div class="title">温馨提示：轻量级服务号不需要添加日程</div>
        <p style="margin-bottom:5px;">服务号类型</p>
        <el-radio-group v-model="serviceObj.Type" @change = "changeRadio">
          <el-radio class="radio" label="normal">普通</el-radio>
          <el-radio class="radio" label="lightweight">轻量级</el-radio>
        </el-radio-group>
      </div>
      <div class="skill-name pb20">
        <p style="margin-bottom:5px;">服务号</p>
        <el-select size="mini" v-model="serviceObj.Exten" placeholder="请选择" filterable>
          <el-option
            v-for="(item, index) in service_no"
            :key="index"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
        <!--<el-input v-model="serviceObj.Exten" placeholder="请输入内容" :disabled="typeFlag">-->
        <!--</el-input>-->
      </div>
      <div class="assign-rule pb20">
        <p style="margin-bottom:5px;">PBX</p>
        <el-select size="mini" v-model="serviceObj.PBX" placeholder="请选择" @change="ToChangePbx" disabled>
          <el-option
            v-for="(item, index) in pbxList"
            :key="index"
            :label="item.name + '('+item._id+')'"
            :value="item._id">
          </el-option>
        </el-select>
      </div>
      <div class="skill-name pb20">
        <p style="margin-bottom:5px;">别名</p>
        <el-input v-model.trim="serviceObj.DisplayName" placeholder="请输入内容"></el-input>
      </div>
      <div v-show="lightFlag">
        <div class="assign-rule pb20">
          <p style="margin-bottom:5px;">流程</p>
          <el-select size="mini" v-model="serviceObj.IvrProcessId" placeholder="请选择" @change="ToChangePeerId" filterable>
            <el-option
              label="不使用流程"
              value="">
            </el-option>
            <el-option
              v-for="(item, index) in toPeerIdArr"
              :key="index"
              :label="item.DisplayName"
              :value="item._id">
            </el-option>
          </el-select>
        </div>
        <div class="assign-rule pb20">
          <p style="margin-bottom:5px;">流转到</p>
          <el-row>
            <el-col :span="11">
              <el-select size="mini" v-model="serviceObj.ToPeer" placeholder="请选择" @change="ToChangePeer" :disabled="flagPerr" filterable>
                <el-option
                  v-for="(item, index) in toPeerTypeArr"
                  :key="index"
                  :label="item.TypeName"
                  :value="item.TypeValue">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span='2' class = 'bat'>
              —
            </el-col>
            <el-col :span="11">
              <el-select size="mini" v-model="serviceObj.ToPeerType" placeholder="请选择"  :disabled="flagPerr" filterable>
                <el-option
                  v-for="(item, index) in systemPeerTypeArr"
                  :key="index"
                  :label="item.name"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="footer-btn">
        <el-button @click="cancelClick" class='primary_btn'>取消</el-button>
        <el-button type="primary" @click="submit" class='primary_btn'>保存</el-button>
      </div>
    </div>
  </div>
</template>
<script>
  import {deepClone} from '@/utils/m7Utils'
  export default {
    name: 'addService',
    data () {
      return {
        flagPerr: false,
        toPeerIdArr: [],
        toPeerTypeArr: [
          {TypeValue: 'system', TypeName: this.$t('configLazyLoad.process.node')},
          {TypeValue: 'ivr_node_queue', TypeName: '技能组'},
          {TypeValue: 'account_user', TypeName: '座席'},
          {TypeValue: 'ivr_node_announcement', TypeName: '播放语音节点'},
          {TypeValue: 'ivr_node_text_announcement', TypeName: '播放文本语音节点'},
          {TypeValue: 'ivr_node_ivr', TypeName: '按键菜单节点'},
          {TypeValue: 'ivr_node_encrypt_md5', TypeName: 'MD5加密节点'},
          {TypeValue: 'ivr_node_validation', TypeName: '采集输入节点'},
          {TypeValue: 'ivr_node_assignment', TypeName: '赋值节点'},
          {TypeValue: 'ivr_node_route', TypeName: '按变量路由节点'},
          {TypeValue: 'ivr_node_ivr_menu', TypeName: '转IVR菜单节点'},
          {TypeValue: 'ivr_node_call_url', TypeName: 'CallUrl节点'},
          {TypeValue: 'ivr_node_date', TypeName: this.$t('configLazyLoad.process.node8')},
          {TypeValue: 'ivr_node_twowaycall', TypeName: '双向回呼节点'},
          {TypeValue: 'ivr_node_asr', TypeName: '语音识别节点'},
          {TypeValue: 'ivr_node_voice_mail', TypeName: '留言节点'},
          {TypeValue: 'ivr_node_room', TypeName: '会议室节点'},
          {TypeValue: 'ivr_node_satisfaction', TypeName: '自定义满意度节点'},
          {TypeValue: 'ivr_node_superDialJobNum', TypeName: '采集工号并拨打节点'},
          {TypeValue: 'ivr_node_extension_peer', TypeName: '自定义节点'}
        ],
        systemPeerTypeArr: [],
        systemPeerTypeArr1: [
          {name: '挂机', value: '0'},
          {name: '满意度调查', value: '1'},
          {name: '拨工号', value: '2'}
        ],
        toPeerArr: [],
        service_no: [],
        lightFlag: false,
        flag: false,
        serviceObj: {
          Account: '',
          DisplayName: '',
          PBX: '',
          Type: 'normal',
          Exten: '',
          _id: '',
          ToPeer: '',
          ToPeerType: '',
          IvrProcessId: ''
        },
        pbxList: []
      }
    },
    props: {
      availableService: Array
    },
    methods: {
//      改变流程 修改流转到的数据
      ToChangePeerId (val) {
        if (val) {
          this.flagPerr = true
          this.toPeerIdArr.forEach(item => {
            if (item._id === val) {
              this.systemPeerTypeArr = []
              this.flowOptionsChange(item.FirstNodeType, this.systemPeerTypeArr)
              this.serviceObj.ToPeerType = item.FirstNode
              this.serviceObj.ToPeer = item.FirstNodeType
            }
          })
        } else {
//          流程到是否可点击
          this.flagPerr = false
          this.serviceObj.IvrProcessId = ''
          this.serviceObj.ToPeer = this.toPeerTypeArr[0].TypeValue
          this.systemPeerTypeArr = this.systemPeerTypeArr1
          this.serviceObj.ToPeerType = this.systemPeerTypeArr[0].value
        }
      },
      flowOptionsChange (val, options) {
        let toPeerArr = this.$store.state.session.ivrMap[this.serviceObj.PBX].data[val]
        if (!val || val === 'system') {
          this.systemPeerTypeArr1.forEach(item => {
            options.push({name: item.name, value: item.value})
          })
        } else {
          options.push({name: '--请选择--', value: ''})
          if (toPeerArr) {
            if (val === 'account_user') {
              toPeerArr.forEach(item => {
                options.push({name: item.displayName, value: item._id})
              })
            } else {
              toPeerArr.forEach(item => {
                options.push({name: item.DisplayName, value: item.Exten})
              })
            }
          }
        }
      },
//      改变流转到数据
      ToChangePeer (val) {
        this.systemPeerTypeArr = []
        if (val === 'system') {
          this.systemPeerTypeArr = this.systemPeerTypeArr1
          this.serviceObj.ToPeerType = this.systemPeerTypeArr[0].value
        } else {
          this.flowOptionsChange(val, this.systemPeerTypeArr)
          if (val === this.serviceObj.ToPeer) {
            if ((this.serviceObj.ToPeerType !== '0') && (this.serviceObj.IvrProcessId !== '')) {
              this.serviceObj.ToPeerType = this.serviceObj.ToPeerType
            } else {
              this.serviceObj.ToPeerType = this.systemPeerTypeArr[0].value
            }
          }
        }
      },
//    初始化流程 toPeerIdArr
      handlePerrIdData () {
        let arr = this.$store.state.session.ivrMap[this.serviceObj.PBX].data.ivr_process
        arr.forEach(item => {
          let obj = {
            FirstNode: item.FirstNode,
            FirstNodeType: item.FirstNodeType,
            _id: item._id,
            DisplayName: item.DisplayName
          }
          this.toPeerTypeArr.forEach(item1 => {
            if (item1.TypeValue === item.FirstNodeType) {
              obj.DisplayName = obj.DisplayName + '(' + item1.TypeName
            }
          })
          let toPeerArr = this.$store.state.session.ivrMap[this.serviceObj.PBX].data[item.FirstNodeType]
          toPeerArr.forEach(item2 => {
            if (item.FirstNodeType === 'account_user') {
              if (item2._id === item.FirstNode) {
                obj.DisplayName = obj.DisplayName + ' - ' + item2.displayName + ')'
              }
            } else {
              if (item2.Exten === item.FirstNode) {
                obj.DisplayName = obj.DisplayName + ' - ' + item2.DisplayName + ')'
              }
            }
          })
          this.toPeerIdArr.push(obj)
        })
      },
//    changge Pbx 初始化流程
      fetchPeerData () {
        this.toPeerIdArr = []
        this.handlePerrIdData()
        this.serviceObj.IvrProcessId = ''
        this.serviceObj.ToPeer = this.toPeerTypeArr[0].TypeValue
        this.serviceObj.ToPeerType = this.systemPeerTypeArr[0].value
      },
      getAllNodesPbx (item) {
        if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[item]) {
          this.fetchPeerData()
        } else {
          let data = {}
          data.Account = this.$store.state.session.account.account
          data.PBX = this.serviceObj.PBX
          this.$store.dispatch('getAllNodesByPbxForSkill', data).then(res => {
            this.fetchPeerData()
          })
        }
      },
//    改变PBX
      ToChangePbx () {
        if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[this.serviceObj.PBX]) {
          this.fetchPeerData()
        } else {
          let data = {}
          data.Account = this.$store.state.session.account.account
          data.PBX = this.serviceObj.PBX
          this.$store.dispatch('getAllNodesByPbxForSkill', data).then(res => {
            this.fetchPeerData()
          })
        }
      },
//      是添加还是修改 处理this.serviceObj的回显值
      changeData () {
        this.serviceObj = {
          Account: '',
          DisplayName: '',
          PBX: this.currentPBX,
          Type: 'normal',
          Exten: this.service_no[0],
          _id: '',
          ToPeer: this.toPeerTypeArr[0].TypeValue,
          ToPeerType: this.systemPeerTypeArr[0].value,
          IvrProcessId: ''
        }
        this.toPeerIdArr = []
        this.handlePerrIdData()
      },
//      切换服务号类型
      changeRadio () {
        if (this.serviceObj.Type === 'normal') {
          this.lightFlag = false
        } else {
          this.lightFlag = true
        }
      },
      submit () {
        let data = {}
        if (!this.serviceObj.PBX) {
          this.$message.error('PBX必填！')
          return
        } else if (!this.serviceObj.Exten) {
          this.$message.error('服务号必填！')
          return
        }
        if (this.serviceObj.Type === 'normal') {
          data = {
            Account: this.$store.state.session.account.account,
            PBX: this.serviceObj.PBX,
            Type: this.serviceObj.Type,
            Exten: this.serviceObj.Exten,
            DisplayName: this.serviceObj.DisplayName
          }
          this.$store.dispatch('saveServiceNo', data).then((res) => {
            if (res && res.success) {
              this.$message.success('添加成功！')
              this.$emit('addRefresh', {Exten: this.serviceObj.Exten, typeFlag: false, service_no: this.service_no, PBX: this.serviceObj.PBX})
            } else {
              this.$message.error('添加失败！')
            }
          })
        } else {
          data = {
            Account: this.$store.state.session.account.account,
            PBX: this.serviceObj.PBX,
            Type: this.serviceObj.Type,
            Exten: this.serviceObj.Exten,
            DisplayName: this.serviceObj.DisplayName,
            IvrProcessId: this.serviceObj.IvrProcessId,
            ToPeerType: this.serviceObj.ToPeer,
            ToPeer: this.serviceObj.ToPeerType
          }
          this.$store.dispatch('saveLightServiceNo', data).then((res) => {
            if (res && res.success) {
              this.$message.success('添加成功！')
              this.$emit('addRefresh', {Exten: this.serviceObj.Exten, typeFlag: false, service_no: this.service_no, PBX: this.serviceObj.PBX})
            } else {
              this.$message.error('添加失败！')
            }
          })
        }
      },
      cancelClick () {
        this.$emit('cancelClick')
      }
    },
    watch: {
      availableService () {
        this.service_no = []
        console.log(this.service_no)
        console.log(this.availableService)
        this.service_no = deepClone(this.availableService)
      },
      currentPBX (newPBX) {
        this.serviceObj.PBX = newPBX
      }
    },
    beforeMount () {
      this.systemPeerTypeArr = deepClone(this.systemPeerTypeArr1)
      this.pbxList = deepClone(this.$getCache('accountPbx'))
      this.service_no = []
      this.service_no = deepClone(this.availableService)
      this.changeData()
    },
    computed: {
      currentPBX () {
        return this.$store.state.config.callCenter.currentPBX
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .title
    color $c-prompt
    margin-bottom 10px
  .add-service
    position relative
    height 100%
    .add-service__con
      height 100%
      overflow-y auto
      padding 20px 20px 60px
      box-sizing border-box
      .footer-btn
        position absolute
        bottom 0
      .footer-btn
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        z-index: 30;
        background: #fff;
        box-shadow: 0px -2px 4px 0px rgba(5,49,38,0.05);
        border-top: 1px solid #e8e8e8;
        display: -ms-flexbox;
        display: flex;
        -ms-flex-pack: center;
        justify-content: center;
        padding: 13px 0;
        box-sizing: border-box;
    .el-input,.el-select
      width 100%
    .skill-name,.assign-rule
      float left
      width 100%
      .bat
       text-align center
       color #DCDFE6
       line-height 30px
    .skill-name
      margin-right 30px
    .ismemory
      clear both
    .pb20
      padding-bottom 20px
    .tishi
      color $c-prompt
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
</style>
